package com.tyrone.gateway.transport;

import com.tyrone.gateway.transport.config.DispatchClientChannelInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DispatchClient {
    Bootstrap client = null;
    NioEventLoopGroup eventExecutors = new NioEventLoopGroup(10);


    //调用
    public FullHttpResponse call(Invoke invoke) throws Exception {
        FullHttpResponse response = null;
        CompletableFuture<FullHttpResponse> future = new CompletableFuture<>();
        client = new Bootstrap()
                .group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new LoggingHandler())
                .handler(new DispatchClientChannelInitializer(future));
        try {
            Channel ch = client.connect(invoke.host, invoke.port).sync().channel();
            // Prepare the HTTP request.
            HttpRequest request = InvokeUtils.convertToHttpRequest(invoke);
            ch.writeAndFlush(request);
            // Wait for the server to close the connection.
            ch.closeFuture().sync();

        } catch (Exception e) {

        } finally {
            // Shut down executor threads to exit.

        }
        return future.get(30, TimeUnit.SECONDS);
    }


    public static void main(String[] args) throws Exception {
        DispatchClient dispatchClient = new DispatchClient();
        Invoke invoke = new Invoke();
        invoke.setHost("127.0.0.1");
        invoke.setPort(8080);
        invoke.setRawPath("/test");

        FullHttpResponse response = dispatchClient.call(invoke);
        System.out.println(response);
    }
}
